package dolf.window;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

//import dolf.game.Game;
import dolf.game.Level;
import dolf.game.Player;
import dolf.game.Game;

public class MainWindow extends Window{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static MainWindow instance = new MainWindow();
	private static final double VERSION = 0.1;
	
	private MainWindow () {
		super.initialize(SystemMessagesHandler.getInstance().getMessages().getString("title"));
		addWindowListener(new WindowAdapter() {
	        public void windowClosing(WindowEvent evt) {
	            // Exit the application
	            System.exit(0);
	        }
	    });
		initialize();
		//	--------------OOOOOOOOPPPPPPPPPPPTTTTTTTTIIIIIIIIIIOOOOOOOOOONNNNNNNNAAAAAAAALLLLLLLL-------
		/*if(ConfigurationHolder.getInstance().getProperty("runinbackround", "false").compareTo("true") == 0){
		this.addWindowFocusListener(new WindowFocusListener() {

			public void windowGainedFocus(WindowEvent arg0) {
				if (g != null) g.startTimer();
				
			}

			public void windowLostFocus(WindowEvent arg0) {
				if (g != null) g.stopTimer();
				
			}
			});
		}*/
	}
	protected void initialize() { 
		if (ConfigurationHandler.getInstance().getProperty("log_enabled").equals("true")) {
			PrintStream out;
			try {
				out = new PrintStream(new BufferedOutputStream(new FileOutputStream(
								ConfigurationHandler.getInstance().getProperty("log_dir", System.getProperty("user.home")+java.io.File.separator+".dolf")+java.io.File.separator+"dolf.log", true)), true);
				System.setOut(out);
				System.setErr(out);
			} catch (FileNotFoundException e) {
				System.err.println("could not open logfile");
				e.printStackTrace();
			}
			
			//print header
		}
		System.out.print("=====================");
		System.out.print(" Dolf version "+ VERSION+ " loaded ");
		System.out.println("=====================");
		
		ConfigurationHandler.getInstance().initConfig();
		initLookAndFeel();
		
		setMinimumSize(new Dimension(700,500));
		setPreferredSize(new Dimension(700,500));
		setMaximumSize(new Dimension(700,500));
		draw();
	}


	
	public static MainWindow getInstance() {
		return instance;
	}
	
	private JMenuBar initMenu(){
		JMenuBar men = new JMenuBar();
		JMenu file = new JMenu(SystemMessagesHandler.getInstance().getMessages().getString("file"));
		JMenu options = new JMenu(SystemMessagesHandler.getInstance().getMessages().getString("options"));
		JMenu help = new JMenu(SystemMessagesHandler.getInstance().getMessages().getString("help"));
		
		JMenuItem newgame = new JMenuItem(SystemMessagesHandler.getInstance().getMessages().getString("new_game"));
		JMenuItem stopgame = new JMenuItem(SystemMessagesHandler.getInstance().getMessages().getString("stop_game"));
		JMenuItem save = new JMenuItem(SystemMessagesHandler.getInstance().getMessages().getString("save"));
		JMenuItem load = new JMenuItem(SystemMessagesHandler.getInstance().getMessages().getString("load"));
		JMenuItem exit = new JMenuItem(SystemMessagesHandler.getInstance().getMessages().getString("exit"));
		
		JMenuItem sound = new JCheckBoxMenuItem(SystemMessagesHandler.getInstance().getMessages().getString("sound"));
		JMenuItem preferences = new JMenuItem(SystemMessagesHandler.getInstance().getMessages().getString("preferences"));
		
		JMenuItem rules = new JMenuItem(SystemMessagesHandler.getInstance().getMessages().getString("rules"));
		JMenuItem about = new JMenuItem(SystemMessagesHandler.getInstance().getMessages().getString("about"));
		
		//keys
		newgame.setAccelerator(KeyStroke.getKeyStroke('N',InputEvent.CTRL_DOWN_MASK));
		stopgame.setAccelerator(KeyStroke.getKeyStroke('C',InputEvent.CTRL_DOWN_MASK));
		save.setAccelerator(KeyStroke.getKeyStroke('S',InputEvent.CTRL_DOWN_MASK));
		load.setAccelerator(KeyStroke.getKeyStroke('L',InputEvent.CTRL_DOWN_MASK));
		
		preferences.setAccelerator(KeyStroke.getKeyStroke('P',InputEvent.CTRL_DOWN_MASK));

		rules.setAccelerator(KeyStroke.getKeyStroke('R',InputEvent.CTRL_DOWN_MASK));
		about.setAccelerator(KeyStroke.getKeyStroke('A',InputEvent.CTRL_DOWN_MASK));
		
		exit.setAccelerator(KeyStroke.getKeyStroke('Q',InputEvent.CTRL_DOWN_MASK));
		
		if (Game.getInstance() != null && Game.getInstance().isStarted() == true) {
			stopgame.setEnabled(true);
		} else stopgame.setEnabled(false);
		
		//listener
		newgame.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				NewGameWindow.getInstance().draw();
			}
		});
		
		stopgame.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				Game.getInstance().stopGame();
			}
		});
		
		load.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				loadDialog();
			}
		});
		
		save.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				//if (Game != null) 
				saveDialog();
			}
		});

		exit.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				System.exit(0);
			}	
		});
		about.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				AboutWindow.getInstance().draw();
			}
			
		});
		preferences.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e){
				PreferencesWindow.getInstance().draw();
			}
		});
		file.setMnemonic('e');
		options.setMnemonic('o');
		help.setMnemonic('h');
		
		file.add(newgame);
		file.add(stopgame);
		file.add(load);
		file.add(save);
		file.add(exit);
		
		options.add(sound);
		options.addSeparator();
		options.add(preferences);
		
		help.add(rules);
		help.add(about);
				
		men.add(file);
		men.add(options);
		men.add(help);
		return men;
	}
	
	public void draw() {
		getContentPane().removeAll();
		setJMenuBar(initMenu());
		super.initialize(SystemMessagesHandler.getInstance().getMessages().getString("title"));
		
		
		if (Game.getInstance() == null || !(Game.getInstance().isStarted()) ) {
			getContentPane().add(
				new JLabel(
						new ImageIcon(this.getClass().getClassLoader().getResource("dolf/gfx/window/title.png"))),BorderLayout.CENTER );
		}
		else {
			getContentPane().add(Canvas.getInstance(), BorderLayout.CENTER);
			getContentPane().add(PlayerDisplay.getInstance(), BorderLayout.LINE_END);
			getContentPane().add(ScoreDisplay.getInstance(), BorderLayout.PAGE_END);
		}
		pack();
		setLocationRelativeTo(null);
		
	}
	private void loadDialog() {
		String path = ConfigurationHandler.getInstance().getProperty("path_save", System.getProperty("user.home")+java.io.File.separator+".dolf" );
		JFileChooser fileChooser = new JFileChooser(path);
		fileChooser.setDialogTitle(SystemMessagesHandler.getInstance().getMessages().getString("load_saved_game"));
		
		int retVal = fileChooser.showOpenDialog(this);
		if (! (retVal == JFileChooser.APPROVE_OPTION))	{
			return;
		}
		
		File loadFile = fileChooser.getSelectedFile();
		
		// de-serialize selected file
		ObjectInputStream objIn;
		try {
			objIn = new ObjectInputStream(new BufferedInputStream(new FileInputStream(loadFile)));
			Level.setInstance( (Level) objIn.readObject());
			objIn.close();
			
			List<Player> pl = Level.getInstance().getPlayers();
			
			//if (g != null) g.stopTimer();
			//g = new Game(dolf,c,pl, parcours);
			
			draw();

			// initialize player money
			
			for (int i = 0; i < pl.size(); i++) {
				pl.get(i).setMoney(Integer.parseInt(ConfigurationHandler.getInstance().getProperty("money", "100" )));
			}
			
			//g.startTimer();
			
		}
		catch (Exception e) {
			System.err.println("could not read saved game: "+loadFile.toString());
			//System.err.println(e.getMessage());
			//e.printStackTrace();
		}
		
	}
	
	private void saveDialog() {
		String path = ConfigurationHandler.getInstance().getProperty("path_save", System.getProperty("user.home")+java.io.File.separator+".dolf" );
		JFileChooser fileChooser = new JFileChooser(path);
		fileChooser.setDialogTitle(SystemMessagesHandler.getInstance().getMessages().getString("save_current_game"));
		
		//loadDir.setDefaultLocale();
		
		int retVal = fileChooser.showSaveDialog(this);
		if (! (retVal == JFileChooser.APPROVE_OPTION))	{
			return;
		}
		
		File saveFile = fileChooser.getSelectedFile();
		
		// de-serialize selected file
		ObjectOutputStream objOut;
		try {
			objOut = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(saveFile)));
			objOut.writeObject(Level.getInstance());
			
			objOut.close();
		}
		catch (Exception e) {
			System.err.println(e.getMessage());
			e.printStackTrace();
			System.err.println("could not save game: "+saveFile.toString());
		}
	}
	
	
}
